<?php
/**
 * @name          wx-qq-function    
 * @copyright     http://code.google.com/u/wxframework/
 * @version       $Id: global.func.php 29 2009-04-23 02:43:52Z sean.fmais $
 * @author        $Author: sean.fmais $  <fmais@163.com>
 * 
**/

//language
function language($str=0,$lang='sys_lang'){
    global $$lang;
	$re = $$lang;
	if (!is_array($re)){
     require_once('extend.lang.php'); // language page
	 $re = $$lang;
	}
   return $re[$str];
}



//regex of input 
function InRe($Str){
 switch($Str){
  case  "NORE": //no replace
  return 'onkeyup=\'value=((value.replace(/(.).*\1/g,"$1")+value.replace(new RegExp("["+value.replace(/(.).*\1/g,"$1")+"]","g"),"")))\' onbeforepaste=\'value=((value.replace(/(.).*\1/g,"$1")+value.replace(new RegExp("["+value.replace(/(.).*\1/g,"$1")+"]","g"),"")))\'';
  break;
  case  "EN": //english
  return  'onkeyup="value=value.replace(/[^A-Za-z]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^A-Za-z]/g,\'\'))"';
  break;
  case "CH": //chinese
  return 'onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\u4E00-\u9FA5]/g,\'\'))"';
  break;
  case "CHS": //chs letters
  return 'onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\uFF00-\uFFFF]/g,\'\'))"';
  break;
  case "NUM": //numbers
  return 'onkeyup="value=value.replace(/[^\d]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\d]/g,\'\'))"';
  break;
  case "DB": //float
  return 'onkeyup="value=value.replace(/[^\d{n}\.\d{m}]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\d{n}\.\d{m}]/g,\'\'))"';
  break;
  case  "ENNUM": //number and letter
  default:
  return 'onkeyup="value=value.replace(/[\W]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[\W]/g,\'\'))"';
   
  }
}


/**
* 判断是否日期格式
* @param string  $str 			- 输入日期字符串
* @param string $format   	    - 识别格式，默认 Y-m-d
* @return (bool) 
*/
function is_date($str,$format="Y-m-d"){
        $str = trim($str);
        $unixTime = strtotime($str);
        $checkDate = date($format,$unixTime);
		$checkDate2 = str_replace('-0','-',$checkDate);
        if(strcmp($checkDate,$str) == 0 || $checkDate2==$str){ 
                return true;
        }else{
                return false;
        }
}

/**
* 获取Cookie值
* @param string  $noprename 	- Cookie名称
* @param integer $prefix   	    - 是否应用cookie前缀
* @return value 
*/
function mygetcookie($noprename,$prefix=1){
    global $cookiepre;
    $getname = ($prefix ? $cookiepre : '').$noprename;
    return getgpc($getname,'C');
}

/**
* 获取变量值(POST/GET/COOKIE/REQUEST)
* @param string  $k 	-变量名称
* @param string  $t 	-获取方式(P,G,C,R)默认R
* @return value 
*/
function getgpc($k, $t='R') {
	switch($t) {
		case 'P': $var = &$_POST; break;
		case 'G': $var = &$_GET; break;
		case 'C': $var = &$_COOKIE; break;
		case 'R': $var = &$_REQUEST; break;
	}
	return isset($var[$k]) ? (is_array($var[$k]) ? $var[$k] : trim($var[$k])) : NULL;
}

/**
* 获取变量值(POST/GET/COOKIE/REQUEST/FILES)增强版本
* @param string  $key 	-变量名称
* @param string  $type 	-转换类型(integer,string,array,file) 默认integer
* @param string  $var 	-获取方式(P,G,C,R,F)默认R
* @return value 
*/
function _getgpc($key, $type = 'integer', $var = 'R') {
	switch($var) {
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		case 'R': $var = &$_REQUEST; break;
		case 'F': $var = &$_FILES; break;
	}
	switch($type) {
		case 'integer':
			$return = isset($var[$key]) ? intval($var[$key]) : 0;
			break;
		case 'string':
			$return = isset($var[$key]) ? $var[$key] : NULL;
			break;
		case 'array':
			$return = isset($var[$key]) ? $var[$key] : array();
			break;
		case 'file':
			$return = isset($var[$key]) ? $var[$key] : NULL;
			break;
		default:
			$return = isset($var[$key]) ? intval($var[$key]) : 0;
	}
	return $return;
}


/**
* 设定Cookie方法(前缀$prefix)
* @param string  $var 	- cookie名称
* @param string  $value -cookie值
* @param integer $life  - cookie存活期
* @param integer $prefix   - 是否应用cookie前缀
* @return void
*/
function mysetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	empty($timestamp) && $timestamp = time();
	setcookie(($prefix ? $cookiepre : '').$var, $value,$life ? $timestamp + $life : 0, $cookiepath,$cookiedomain,$_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

/**
* JavaScript 弹出方法
* @param string  $str 	- 弹出信息
* @param string  $btn 	- 按钮方式 (url 提示并跳转，tourl 直接跳转 ,close 提示并关闭,back 提示并返回)
* @param integer $halt  - 是否强制终止程序
* @param string  $url   - 跳转路径
* @return void
*/
function alert($str='',$btn='back',$halt=0,$url='/index.htm'){
    if ($halt){echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';}
    switch ($btn){
		case "url":
 		  $t_m_p .= "<script language=\"javascript\" type=\"text/javascript\">alert('".$str."');location.href='".$url."';</script>";
		  break; 
		case "tourl":
 		  $t_m_p .= "<script language=\"javascript\" type=\"text/javascript\">location.href='".$url."';</script>";
		  break; 
		case "close":
 		  $t_m_p .= "<script language=\"javascript\" type=\"text/javascript\">alert('".$str."');window.close();</script>";
		  break; 
		case "back":
 		  $t_m_p .= "<script language=\"javascript\" type=\"text/javascript\">alert('".$str."');history.back(1);</script>";
		  break; 
		default:
 		  $t_m_p .= "<script language=\"javascript\" type=\"text/javascript\">alert('".$str."');</script>";
	}
 	 echo $t_m_p;
	 if ($halt){exit;}
	 
}


/**
* 获取在线IP
* @return string 
*/
function myonlineip(){
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	
	preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
	$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	unset($onlineipmatches);
	return $onlineip;
}

/**
* 自定义 addslashes()
* @param string  $string - 字符值
* @param integer $force  - 是否强制转换反斜杠,0 为false,1为true
* @return string
*/
function myaddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = myaddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}

/**
* 判断客户端是否属于bot类型
* @return (bool) 常量IS_ROBOT
*/
function getrobot() {
	if(!defined('IS_ROBOT')) {
		$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
		if(preg_match("/($kw_browsers)/", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', FALSE);
		} elseif(preg_match("/($kw_spiders)/", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', TRUE);
		} else {
			define('IS_ROBOT', FALSE);
		}
	}
	return IS_ROBOT;
}

/**
* 自定义 htmlspecialchars()
* @param string  $string - 字符值
* @return string
*/
function myhtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = myhtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

/**
* 字符截取
* @param string  $string - 字符值
* @param integer $length - 保留字符长度
* @param string  $dot    - 省略符号 默认: ...
* @return string
*/
function cutstr($string, $length, $dot = ' ...') {
	global $charset;
	if(strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if(strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {break;}

		}
		if($noc > $length) {$n -= $tn;}
		$strcut = substr($string, 0, $n);
	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

/**
* 错误的日志处理
* @param string  $type     	 - 日志文件名
* @param string  $message  	 - 错误信息
* @param integer $halt     	 - 处理是否退出程序, 默认：1为退出 ， 0为继续 
* @param string  $timestamp  - 报错时间
* @return void
*/
function errorlog($type, $message, $halt = 1,$timestamp='') {
	global $onlineuser, $onlineip, $_SERVER;
	empty($timestamp) && $timestamp = time();
	$user = empty($onlineuser) ? '' : $onlineuser.'<br />';
	$user .= $onlineip.'|'.$_SERVER['REMOTE_ADDR'];
	writelog('errorlog',myhtmlspecialchars("$timestamp\t$type\t$user\t".str_replace(array("\r", "\n"), array(' ', ' '), trim($message))));
	if($halt) {
		exit();
	}
}

/**
* 写入日志文件
* @param string  $file       - 日志文件名
* @param string  $log        - 日志日容
* @param string  $timestamp  - 日志时间
* @return void
*/
function writelog($file, $log,$timestamp='') {
	empty($timestamp) && $timestamp = time();
	echo $timestamp;
	$yearmonth = gmdate('Ym', $timestamp);
	
	$logdir =LOG_PATH;
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $tmp)."\n");
		}
		fclose($fp);
	}
}

/**
* 字符串检索
* @param string  $haystack - 被检索字符串
* @param string  $needle   - 需要检索的关键字或串
* @return (bool)
*/
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}

/**
* 日期比较差
* @param datetime  $date1   - 日期1 （time）
* @param datetime  $date2   - 日期2 （time）
* @param string    $unit    - 比较类型 
* @return  float
*/
function datediff($date1, $date2, $unit = "") { 
	 switch ($unit) {
		  case 's':
		   $dividend = 1;
		   break;
		  case 'i':
		   $dividend = 60;
		   break;
		  case 'h':
		   $dividend = 3600;
		   break;
		  case 'd':
		   $dividend = 86400;
		   break;
		  default:
		   $dividend = 86400;
	 }
	 
	 $time1 = strtotime($date1);
	 $time2 = strtotime($date2);
	 
	 if ($time1 && $time2){return (float)($time1 - $time2) / $dividend;}
	 
	 return false;
} 

/**
 * 带公钥的快速加码解码(ENCODE/DECODE）
 * 示例： list($uid,$username,$password) = myaddslashes(explode("\t", authcode($auth, 'DECODE')), 1);
 * @param string  $string     - 密文
 * @param string  $operation  - 方式 (ENCODE / DECODE)默认DECODE
 * @param string  $key 		  - 公钥字符(默认为常量SYS_KEY的值)
 * @param integer  $expiry 	  - 有效期
 * @return string
**/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;
	$key = md5($key ? $key : SYS_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}



/**
* json to string
* @param string  string  $str  
* @return (object)JSON-formatted
*/
if(!function_exists("json_decode")){
	function json_decode($json){
		require_once(CLS_PATH.'json_class.php');
		$obj = new Services_JSON;
		$str = $obj->decode($json);
		return $str;
	}
}

/**
* array to json
* @param array  $array  $array
* @return JSON-formatted string
*/
if(!function_exists("json_encode")){
	function json_encode($array){
		require_once(CLS_PATH.'json_class.php');
		$obj = new Services_JSON;
		$json = $obj->encode($array);
		return $json;
	}
}



/**
*	//加密解密部分 示例
*	$enc_text = base64_encode(encrypt($string,$key));
*	setcookie("loginpwd",$enc_text, time()+3600);
*	$cookiesvalue = base64_decode($_COOKIE['loginpwd']);
*	$dec_text = decrypt($cookiesvalue,$key);
*/
function keyED($txt,$encrypt_key){
	$encrypt_key = md5($encrypt_key);
	$ctr=0;
	$tmp = "";
	for ($i=0;$i<strlen($txt);$i++)
	{
	if ($ctr==strlen($encrypt_key)) $ctr=0;
	$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
	$ctr++;
	}
	return $tmp;
}

function encrypt($txt,$key){
	srand((double)microtime()*1000000);
	$encrypt_key = md5(rand(0,32000));
	$ctr=0;
	$tmp = "";
	for ($i=0;$i<strlen($txt);$i++)
	{
	if ($ctr==strlen($encrypt_key)) $ctr=0;
	$tmp.= substr($encrypt_key,$ctr,1) .
	(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
	$ctr++;
	}
	return keyED($tmp,$key);
}

function decrypt($txt,$key){
	$txt = keyED($txt,$key);
	$tmp = "";
	for ($i=0;$i<strlen($txt);$i++)
	{
	$md5 = substr($txt,$i,1);
	$i++;
	$tmp.= (substr($txt,$i,1) ^ $md5);
	}
	return $tmp;
}
//加密解密结束


?>